package com.abc.easyclaim;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.abc.bean.Case;
import com.abc.bean.Photo;
import com.abc.db.DBManager;
import com.abc.tool.StringTool;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ViewFlipper;

public class Camera extends Activity implements OnClickListener,OnGestureListener{
	private Case caze;
	private final int FLIP_DISTANCE=50;        //定义手势动作两点间的最小距离
	private Boolean isreedit=false;           //重新编辑的标记
	private Boolean retakePhoto=false;        //重新拍照标记
	private ViewFlipper flipper;
	private LinearLayout pageLayout;
	private PopupWindow popupWindow;
	private static final String KEY="key";
	private ListView listView;
	private ArrayList<Map<String, Object>> items=new ArrayList<Map<String,Object>>();
	// 定义手势检测器实例
	GestureDetector detector;
	Animation[] animations=new Animation[4]; 
	TextView photoTitle;
	private Button returnButton;           //返回按钮
	private Button operateButton;          //操作菜单按钮
	int currentPhoto=0;          //表示现在在显示第几张照片
	private ArrayList<String> photoCommentStrings=new ArrayList<String>();    //照片评论集合
	private ArrayList<String> photoNameStrings=new ArrayList<String>();     //照片名称集合
	private List<Photo> photos=new ArrayList<Photo>();           //照片类合集
	private List<Bitmap> bitmaps=new ArrayList<Bitmap>();           //照片合集
	private List<String> photoSizes=new ArrayList<String>();         //照片大小合集
	private List<Date> photoDates=new ArrayList<Date>();          //照片拍照时间合集 
	private List<byte[]> dataBytes=new ArrayList<byte[]>();         //照片字节数据合集
	private List<View> flipperViews=new ArrayList<View>();
	private List<ImageView> pageImageViews=new ArrayList<ImageView>();
	DBManager dbManager;                 //数据库管理器
	//存储照片的文件夹路径
	String photoFolderPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera);
		//获取组件
		flipper=(ViewFlipper)findViewById(R.id.flipper);
		pageLayout=(LinearLayout)findViewById(R.id.pagedots);
		returnButton=(Button)findViewById(R.id.exit_camera);
		operateButton=(Button)findViewById(R.id.operate_menu);
		photoTitle=(TextView)findViewById(R.id.photo_title);
		
		//为按钮添加监听器
		returnButton.setOnClickListener(this);	
		operateButton.setOnClickListener(this);
		// 创建手势检测器
		detector = new GestureDetector(this, this);
		//初始化Animation数组
		animations[0]=AnimationUtils.loadAnimation(this, R.anim.left_in);
		animations[1]=AnimationUtils.loadAnimation(this, R.anim.left_out);
		animations[2]=AnimationUtils.loadAnimation(this, R.anim.right_in);
		animations[3]=AnimationUtils.loadAnimation(this, R.anim.right_out);
		init();		
	}

	//初始化显示照片
	private void init() {
		photoFolderPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/";
		dbManager=new DBManager(getBaseContext());
		caze = dbManager.queryCase(MainApplication.getCurrentCaseId());
		photoFolderPath = new String(photoFolderPath+caze.getName()+"/photos");
		System.out.println("MainApplication.getCurrentCaseId()="+MainApplication.getCurrentCaseId());
		photos=dbManager.queryPhotos(MainApplication.getCurrentCaseId());
		System.out.println("photos.size()="+photos.size());
		for (int i = 0; i < photos.size(); i++) {
			photoCommentStrings.add(i, photos.get(i).getDescription());
			photoNameStrings.add(i, photos.get(i).getTitle());
			photoDates.add(i, photos.get(i).getDate());
			photoSizes.add(i, photos.get(i).getSize());
			String photoPath= photoFolderPath+"/"+photos.get(i).getTitle();
			System.out.println("photoPathsyb="+photoPath);
			Bitmap bitmap=BitmapFactory.decodeFile(photoPath);
			bitmaps.add(i, bitmap);					
			try {
				ByteArrayOutputStream baos=new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				System.out.println("sdfgsdg="+baos.toByteArray());
				dataBytes.add(i, baos.toByteArray());
				baos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			flipperViews.add(i, createView(i));
			flipper.addView(flipperViews.get(i),i);
		    pageImageViews.add(i, createImageView(i));
			pageLayout.addView(pageImageViews.get(i),i);
		}	
		if (photos.size()>0) {
			photoTitle.setText(1+"/"+photos.size());		
		}
		else {
			photoTitle.setText("没有照片！");
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		//“返回”按钮
		if (id == R.id.exit_camera) {
			finish();
		}
		//“操作”按钮
		else if (id == R.id.operate_menu) {
		    showPopupWindow(v);  //显示窗口
		}
	}

	private void showPopupWindow(View parent) {
		if (popupWindow ==null) {
			View view=LayoutInflater.from(this).inflate(R.layout.photo_pop, null);
			listView=(ListView)view.findViewById(R.id.pop_list);
			SimpleAdapter adapter=new SimpleAdapter(this, createList(), R.layout.photo_pop_listitem, new String[]{KEY}, new int[]{R.id.photo_menuitem});
			listView.setAdapter(adapter);
			listView.setItemsCanFocus(false);
			//listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					switch (arg2) {
					case 0:       //开始拍照
						System.out.println("currentPhoto="+currentPhoto);
						Intent intent=new Intent(Camera.this, CameraPreview.class);   //进入对焦拍照界面
						Bundle bundle=new Bundle();
						bundle.putStringArrayList("photoNameStrings", photoNameStrings);  //传入照片名称集合用于判断是否重名
						bundle.putInt("currentPhoto", currentPhoto);              //传入当前是第几张照片
						intent.putExtras(bundle);
						startActivityForResult(intent, 1);
						popupWindow.dismiss();
						break;
					case 1:          //重新拍照
						if (currentPhoto < bitmaps.size()) {
							System.out.println("currentPhoto="+currentPhoto);
							Intent intent2=new Intent(Camera.this, CameraPreview.class);   //进入对焦拍照界面
							Bundle bundle2=new Bundle();
							bundle2.putBoolean("retakephoto", true);         //传入重新拍照的标记
							bundle2.putInt("currentPhoto", currentPhoto);              //传入当前是第几张照片
							intent2.putExtras(bundle2);
							startActivityForResult(intent2, 6);
						}
						popupWindow.dismiss();
						break;
                    case 2:        //重新编辑
                    	if (currentPhoto < bitmaps.size()) {
                    		System.out.println("currentPhoto="+currentPhoto);
                			Intent intent1 =new Intent(Camera.this,PhotoComment.class);
                			Bundle bundle1=new Bundle();
                			bundle1.putStringArrayList("photoNameStrings", photoNameStrings);  //传入照片名称集合用于判断是否重名
                			bundle1.putInt("currentPhoto", currentPhoto);              //传入当前是第几张照片
                			bundle1.putByteArray("data", dataBytes.get(currentPhoto));   //传入当前页照片的字节数据
                			bundle1.putString("photoDate", StringTool.date2String(photoDates.get(currentPhoto), "yyyy-MM-dd HH:mm:ss"));
                			bundle1.putString("recomment", photoCommentStrings.get(currentPhoto));  //传入当前页照片的评论
                			bundle1.putBoolean("isreedit", true);                    //传入重新编辑的标记
                			intent1.putExtras(bundle1);
                		    startActivityForResult(intent1, 3);
						}                  	
            		    popupWindow.dismiss();
                    	break;
                    case 3:        //删除
                    	if (currentPhoto < bitmaps.size()) {
                    		deletePhoto();
                			//删除数据库中记录
                			dbManager.deletePhoto(photos.get(currentPhoto));
                			photos=dbManager.queryPhotos(MainApplication.getCurrentCaseId());
                			System.out.println("currentPhoto="+currentPhoto);
                			if (currentPhoto>0) {			
                				if (currentPhoto==bitmaps.size()) {   //删除最后一张则往前显示，否则显示后面的
                					currentPhoto--;
    							}
                				System.out.println("currentPhoto="+currentPhoto);
                				pageImageViews.get(currentPhoto).setEnabled(false);
                				photoTitle.setText((currentPhoto+1)+"/"+bitmaps.size());
                			}
                			else if (bitmaps.size()>0) {
                				pageImageViews.get(currentPhoto).setEnabled(false);
                				photoTitle.setText((currentPhoto+1)+"/"+bitmaps.size());
                			}
                			else {
                				photoTitle.setText("没有照片！");
                			}
						}
            			popupWindow.dismiss();
						break;
					case 4:           //隐藏菜单
						popupWindow.dismiss();
						break;
					}
				}
			});
			popupWindow=new PopupWindow(view, 150, 300);
		}
		popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.update();
		popupWindow.showAsDropDown(parent);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode==20) {
			isreedit=data.getBooleanExtra("isreedit", false);          //接收返回的是否是重新编辑的标记
			retakePhoto=data.getBooleanExtra("retakephoto", false);   //接收返回的重新拍照标记
			int saveCurrent=currentPhoto;        //记录之前所在页面
			currentPhoto=data.getIntExtra("currentPhoto", currentPhoto);    //获取新页面
			System.out.println("isreedit="+isreedit);
			System.out.println("currentPhoto="+currentPhoto);
			if (currentPhoto==bitmaps.size() && currentPhoto!=0) {
				pageImageViews.get(saveCurrent).setEnabled(true);   //原页面对应白点变黑点
			}
			//如果是重新编辑或者重新拍照，则要替代本页原来的数据，故要先删除本页原来的数据
			if (isreedit || retakePhoto) {
				deletePhoto();
			}
			//接收返回的刚拍的照片
			dataBytes.add(currentPhoto, data.getByteArrayExtra("pic"));
			if (dataBytes.get(currentPhoto)!=null) {
				Bitmap bm=BitmapFactory.decodeByteArray(dataBytes.get(currentPhoto), 0, dataBytes.get(currentPhoto).length);         
				bitmaps.add(currentPhoto, bm);          //保存到图片数组中
				int bmWidth=bm.getWidth();        //图片的宽
				int bmHeight=bm.getHeight();      //图片的高
				photoSizes.add(currentPhoto, bmWidth+"x"+bmHeight);    //保存照片大小
			}
			//不是重新拍照才修改评论和名称
			if (!retakePhoto) {           
				//返回照片评论
				photoCommentStrings.add(currentPhoto,data.getStringExtra("comment"));
				//接收返回的照片名称
				photoNameStrings.add(currentPhoto,data.getStringExtra("name")+".jpg");	
			}
			//接收返回的拍照时间
			System.out.println("currentPhoto="+currentPhoto);
			photoDates.add(currentPhoto, StringTool.string2Date(data.getStringExtra("photoDate"), "yyyy-MM-dd HH:mm:ss"));
			flipperViews.add(currentPhoto, createView(currentPhoto));
			flipper.addView(flipperViews.get(currentPhoto),currentPhoto);
			for(;saveCurrent<currentPhoto;saveCurrent++) {
				flipper.showNext();	
			}	
			if (isreedit || retakePhoto) {
				if (currentPhoto==(bitmaps.size()-1)) {
					flipper.showNext();
				}
				else {
					flipper.showPrevious();
				}
			}
			pageImageViews.add(currentPhoto, createImageView(currentPhoto));
			pageLayout.addView(pageImageViews.get(currentPhoto), currentPhoto);
			pageImageViews.get(currentPhoto).setEnabled(false);
			photoTitle.setText((currentPhoto+1)+"/"+bitmaps.size());		
			data.getExtras().remove("pic");
			data.getExtras().remove("comment");
			data.getExtras().remove("name");
			data.getExtras().remove("isreedit");
			data.getExtras().remove("photoDate");
			data.getExtras().remove("currentPhoto");
			data.getExtras().remove("retakephoto");
			System.gc();
			
			//保存照片等
			File folder=new File(photoFolderPath);         //创建保存照片的文件夹
			if (!folder.exists()) {
				folder.mkdirs();
			}
			File file=new File(photoFolderPath+"/"+photoNameStrings.get(currentPhoto));	
			FileOutputStream outputStream=null;
			try {
				//打开指定文件对应的输出流
				outputStream=new FileOutputStream(file);
				//把位图输出到指定文件中
				bitmaps.get(currentPhoto).compress(CompressFormat.JPEG, 100, outputStream);
				outputStream.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			//保存到数据库中
			Photo photo=new Photo();
			if (isreedit || retakePhoto) {
				photo.setId(photos.get(currentPhoto).getId());       
			}
			photo.setTitle(photoNameStrings.get(currentPhoto));           //照片名
			photo.setDescription(photoCommentStrings.get(currentPhoto));   //照片评论
			photo.setPath(photoFolderPath);          //路径名
			photo.setSize(photoSizes.get(currentPhoto));           //照片大小
			photo.setDate(photoDates.get(currentPhoto));      //拍照日期
			photo.setCaseId(MainApplication.getCurrentCaseId());
			if (isreedit || retakePhoto) {
				dbManager.modifyPhoto(photo);          //编辑模式修改照片
			}
			else {
				dbManager.addPhoto(photo);            //非编辑模式添加照片
			}		
			photos=dbManager.queryPhotos(MainApplication.getCurrentCaseId());
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	//删除照片等函数
	private void deletePhoto(){
		System.out.println("currentPhoto="+currentPhoto);
		System.out.println("photoNameStrings.get(currentPhoto)="+photoNameStrings.get(currentPhoto));
		//删除存储路径的文件
		File photoFile=new File(photoFolderPath+"/"+photoNameStrings.get(currentPhoto));
		photoFile.delete();		
		//删除list中的数据	
		if (!retakePhoto) {                   //不是重新拍照
			photoCommentStrings.remove(currentPhoto);
			photoNameStrings.remove(currentPhoto);
		}		
		photoDates.remove(currentPhoto);
		photoSizes.remove(currentPhoto);
		bitmaps.remove(currentPhoto);
		dataBytes.remove(currentPhoto);
		flipper.removeView(flipperViews.get(currentPhoto));
		flipperViews.remove(currentPhoto);
		pageLayout.removeView(pageImageViews.get(currentPhoto));
		pageImageViews.remove(currentPhoto);
	}
	
	private View createView(int current){
		LayoutInflater layoutInflater = LayoutInflater.from(this);
		LinearLayout resultView=(LinearLayout)layoutInflater.inflate(R.layout.flipperview, null);
		((ImageView)resultView.findViewById(R.id.myImageView)).setImageBitmap(bitmaps.get(current));
		((TextView)resultView.findViewById(R.id.photoSize)).setText(photoSizes.get(current));
		((TextView)resultView.findViewById(R.id.photoDate)).setText(StringTool.date2String(photoDates.get(current), "yyyy-MM-dd HH:mm:ss"));
		((TextView)resultView.findViewById(R.id.photo_description_text)).setVisibility(0);
		System.out.println("photoNameStrings.get(current)="+photoNameStrings.get(current));
		((TextView)resultView.findViewById(R.id.photo_name)).setText(photoNameStrings.get(current));
		((TextView)resultView.findViewById(R.id.photoComment)).setText(photoCommentStrings.get(current));
		return resultView;
	}

	private ImageView createImageView(int current){
		ImageView imageViewDot=new ImageView(this);
		if (current==0) {
			imageViewDot.setEnabled(false);
		}
		else {
			imageViewDot.setEnabled(true);
		}		
		imageViewDot.setImageResource(R.drawable.guide_round);
		imageViewDot.setPadding(15, 0, 15, 0);
		return imageViewDot;
	}
	
	private ArrayList<Map<String, Object>> createList() {
		Map<String, Object> map;
		map=new HashMap<String, Object>();
		map.put(KEY, "开始拍照");
		items.add(map);
		map=new HashMap<String, Object>();
		map.put(KEY, "重新拍照");
		items.add(map);
		map=new HashMap<String, Object>();
		map.put(KEY, "重新编辑");
		items.add(map);
		map=new HashMap<String, Object>();
		map.put(KEY, "删除");
		items.add(map);
		map=new HashMap<String, Object>();
		map.put(KEY, "隐藏菜单");
		items.add(map);
		return items;
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		// 将该Activity上的触碰事件交给GestureDetector处理
		return detector.onTouchEvent(event);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		//如果第一个触点事件的X坐标大于第二个触点事件的X坐标超过FLIP_DISTANCE，也就是手势从左向右滑
		if ((e2.getX()-e1.getX()) > FLIP_DISTANCE) {
			//为flipper设置切换的动画效果
			flipper.setInAnimation(animations[2]);
			flipper.setOutAnimation(animations[3]);		
			if (currentPhoto>0) {
				flipper.showPrevious();
				pageImageViews.get(currentPhoto).setEnabled(true);
				currentPhoto--;
				pageImageViews.get(currentPhoto).setEnabled(false);
				photoTitle.setText((currentPhoto+1)+"/"+bitmaps.size());
			}
			return true;
		}
		//如果第二个触点事件的X坐标大于第一个触点事件的X坐标超过FLIP_DISTANCE，也就是手势从右向左滑
		else if ((e1.getX() - e2.getX()) > FLIP_DISTANCE) {
			//为flipper设置切换的动画效果
			flipper.setInAnimation(animations[0]);
			flipper.setOutAnimation(animations[1]);
			if (currentPhoto<bitmaps.size()-1) {
				flipper.showNext();
				pageImageViews.get(currentPhoto).setEnabled(true);
				currentPhoto++;
				pageImageViews.get(currentPhoto).setEnabled(false);
				photoTitle.setText((currentPhoto+1)+"/"+bitmaps.size());
			}			
			return true;
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
}
